package com.fqr;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

public class FlexQuartzRunner {
	
	public static void main(String[] args) throws Exception {
		FlexSchedule sched = FlexSchedule.getSchedule();
		List<FlexJob> allJobs = sched.getFlexJobs();
		Collections.sort(allJobs, new JobComparator());

		if (args.length > 0) {
			if (args[0].equals("-l")) {
				System.out.println("Available Jobs:");
				int i = 1;
				for (FlexJob gJob : allJobs) {
					System.out.println(i + ") " + gJob.getName());
					i++;
				}
			} else {
				if (args.length >= 2) {
					Date date = DateParser.parse(args[1]);
					Now.set(date);
				}

				String[] fields = args[0].split(",");
				for (String f : fields) {
					int jobNumber = Integer.parseInt(f);
					FlexJob flexJob = allJobs.get(jobNumber - 1);

					System.out.println("Running " + flexJob.getName());
					sched.runJob(flexJob.getName(), null);
				}
			}
		} else {
			sched.start();
			Logger.getLogger(FlexQuartzRunner.class).info("Scheduler is started");
			
			while(true) {
				Thread.sleep(60 * 60 * 1000);
				System.out.println("ping...");
			}
		}
	}

	static class JobComparator implements Comparator<FlexJob> {
		public int compare(FlexJob o1, FlexJob o2) {
			return o1.getName().toUpperCase().compareTo(o2.getName().toUpperCase());
		}
	}

}
